package com.apes.hr.cultivate.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.cultivate.model.Course;
import com.apes.hr.cultivate.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

/**
 * 功能：培训课程
 *
 * @author Linwz
 * @create 2019-06-17 15:11
 */
@Service("hrCourseService")
public class CourseService extends DomainService {
    @Autowired
    public CourseRepository courseRepository;


    /**
     * 功能：创建
     * @param request
     * @return
     */
    public Course save(SimpleRequest request) {
        Course course = request.getO(Course.class);
        cheakLeval(course);
        course.setState("create");  //设置当前的状态
        return courseRepository.saveAndFlush(course);
    }

    /**
     * 检查 课程等级
     * @param course
     */
    private void cheakLeval(Course course){
        course.getCourseLevelSet().forEach(courseLevel -> {
            int valueL = courseLevel.getValueL();
            int valueU =courseLevel.getValueU();
            if(valueL>valueU) throw new RuntimeException("最低分必须小于最高分!");
        });
    }

    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public Course update(SimpleRequest request) {
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        Course course = courseRepository.findOne(id);
        if (course == null) throw new RuntimeException("课程【" + id + "】在系统中不存在。");
        if(course.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
        Course requestCourse = request.getO(Course.class);
        cheakLeval(requestCourse);
        return courseRepository.saveAndFlush(requestCourse);

    }

    /***
     * 功能： 删除
     * @param request
     * @return
     * @throws RuntimeException
     */
    public String delete(SimpleRequest request) throws RuntimeException {
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        Course course = courseRepository.findOne(id);
        if (course == null) throw new RuntimeException("课程【" + id + "】在系统中不存在。");
        if(course.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
        // 设置删除人以及状态
        Course requestCourse = request.getO(Course.class);

        requestCourse.setDeleteId(this.getPerson(request)); //设置人员
        requestCourse.setDeleteDate(new Date()); // 设置时间
        requestCourse.setState("delete");  //设置当前的状态为删除
        courseRepository.saveAndFlush(requestCourse);

        return "删除成功！";
    }


    /***
     * 功能：回车查询
     * @param request
     * @return
     */
    public Course findOne(SimpleRequest request) {
        Course course = courseRepository.findOne((String) request.get("id"));
        return course;
    }

}
